<template>
  <div v-if="mode === 'search'">Loading...</div>
  <div v-else>
    <div v-if="!detail">
      <div v-if="breakout">
        <TableAppointments
          :allowRefresh="false"
          :api="api"
          :appts="appointments"
          :currentUserId="currentUserId"
          :devmode="devmode"
          :filters="'scheduled checked'"
          :loading="loading"
          :searchState="searchStateQueued"
          :teamsForUser="teamsForUser"
          :title="'Queue'"
          :users="users"
          @updateDetail="val => updateDetail(val)"
          @updateSearchState="val => updateSearchStateQueued(val)"
          @refresh="getAppointments()"
        />
        <TableAppointments
          :allowRefresh="false"
          :api="api"
          :appts="appointments"
          :currentUserId="currentUserId"
          :devmode="devmode"
          :filters="'active'"
          :loading="loading"
          :searchState="searchStateActive"
          :teamsForUser="teamsForUser"
          :title="'In Progress'"
          :users="users"
          @updateDetail="val => updateDetail(val)"
          @updateSearchState="val => updateSearchStateActive(val)"
          @refresh="getAppointments()"
        />
        <TableAppointments
          :allowRefresh="false"
          :api="api"
          :appts="appointments"
          :currentUserId="currentUserId"
          :devmode="devmode"
          :filters="'cancel finished no-show'"
          :loading="loading"
          :searchState="searchStateFinished"
          :teamsForUser="teamsForUser"
          :title="'Completed'"
          :users="users"
          @updateDetail="val => updateDetail(val)"
          @updateSearchState="val => updateSearchStateFinished(val)"
          @refresh="getAppointments()"
        />
      </div>

      <div v-else>
        <TableAppointments
          :allowRefresh="false"
          :api="api"
          :appts="appointments"
          :currentUserId="currentUserId"
          :devmode="devmode"
          :filters="''"
          :loading="loading"
          :searchState="searchStateActive"
          :teamsForUser="teamsForUser"
          :title="''"
          :users="users"
          @updateDetail="val => updateDetail(val)"
          @updateSearchState="val => updateSearchStateAll(val)"
          @refresh="getAppointments()"
        />
      </div>
    </div>

    <div v-if="detail">
      <AppointmentModal
        v-bind:currentUserId="currentUserId"
        v-bind:detail="detail"
        v-bind:hasPermission="hasPermission(detail.teamId)"
        v-bind:devmode="devmode"
        v-bind:reassign="api.reassign"
        v-bind:takebegin="api.takebegin"
        v-bind:apptUsers="api.apptUsers"
        @closeSummary="closeSummary()"
        @refresh="getAppointments()"
      />
    </div>
  </div>
</template>

<script>
import AppointmentModal from "@/components/AppointmentModal.vue";
import TableAppointments from "@/components/TableAppointments.vue";
import { mapMutations, mapGetters } from "vuex";

export default {
  name: "appointments",
  components: {
    AppointmentModal,
    TableAppointments
  },
  computed: {
    teamsForUser: function() {
      return this.currentUser
        ? this.currentUser.teams.map(team => team.id)
        : [];
    },
    appointments: function() {
      return this.runtimevals.appointments;
    },
    currentUserId: function() {
      return this.currentUser ? this.currentUser.id : "";
    },
    ...mapGetters([
      "api",
      "breakout",
      "mode",
      "currentUser",
      "devmode",
      "refresh",
      "searchStateQueued",
      "searchStateActive",
      "searchStateFinished",
      "users"
    ])
  },
  methods: {
    ...mapMutations([
      "updateErrorPrompt",
      "updateSearchStateAll",
      "updateSearchStateQueued",
      "updateSearchStateActive",
      "updateSearchStateFinished"
    ]),
    hasPermission(teamId) {
      return this.teamsForUser.map(id => id * 1).includes(teamId * 1);
    },
    updateDetail(val) {
      this.detail = val;
    },
    closeSummary() {
      this.detail = "";
    },
    startTimer() {
      this.timer = setInterval(() => {
        this.getAppointments();
      }, 60000);
    },
    getAppointments: function() {
      function getData(endpoint, that, bucket, refs, errorPrompt) {
        that["loading"] = true;
        if (endpoint) {
          fetch(endpoint)
            .then(response => response.json())
            .then(json => {
              if (json) {
                that[bucket][refs] = json;
                that["loading"] = false;
              } else {
                that[errorPrompt] = "Response failed.";
                that["loading"] = false;
              }
            })
            .catch(error => {
              that[errorPrompt] = `Request failed. ${error}`;
              that["loading"] = false;
            });
        } else {
          that[errorPrompt] = "No configuration.";
          that["loading"] = false;
        }
      }

      getData(
        this.api.appointments,
        this,
        "runtimevals",
        "appointments",
        "errorPrompt"
      );
    }
  },
  mounted() {
    if (this.mode === "search") {
      this.$router.push({ name: "Search" });
    } else {
      this.getAppointments();
      this.startTimer();
    }
  },
  data() {
    return {
      detail: "",
      errorPrompt: "",
      loading: false,
      runtimevals: {
        appointments: "",
        breakout: ""
      },
      timer: ""
    };
  },
  watch: {
    errorPrompt() {
      this.updateErrorPrompt(this.errorPrompt);
    },
    refresh() {
      this.getAppointments();
    }
  }
};
</script>

<style scoped></style>
